from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

# 设置浏览器驱动路径（根据你的实际情况修改）
driver_path = 'path/to/your/chromedriver'

# 初始化浏览器
driver = webdriver.Chrome(executable_path=driver_path)

# 打开12306官网
driver.get('https://www.12306.cn/index/')

try:
    # 等待页面加载完成
    WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "username"))
    )

    # 登录操作
    username = driver.find_element(By.ID, "username")
    password = driver.find_element(By.ID, "password")

    username.send_keys("your_username")  # 替换为你的12306账号
    password.send_keys("your_password")  # 替换为你的12306密码

    # 点击登录按钮
    login_button = driver.find_element(By.ID, "loginSub")
    login_button.click()

    # 等待登录完成
    WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "train_date"))
    )

    # 填写出发地、目的地、日期等信息
    from_station = driver.find_element(By.ID, "fromStationText")
    to_station = driver.find_element(By.ID, "toStationText")
    train_date = driver.find_element(By.ID, "train_date")

    from_station.clear()
    from_station.send_keys("北京")  # 替换为你的出发地
    from_station.send_keys(Keys.ENTER)

    to_station.clear()
    to_station.send_keys("上海")  # 替换为你的目的地
    to_station.send_keys(Keys.ENTER)

    train_date.clear()
    train_date.send_keys("2023-12-31")  # 替换为你的出发日期

    # 点击查询按钮
    query_button = driver.find_element(By.ID, "query_ticket")
    query_button.click()

    # 等待查询结果
    WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "ticketList"))
    )

    # 尝试抢票
    buy_button = driver.find_element(By.CLASS_NAME, "btn72")
    buy_button.click()

    # 等待抢票页面加载
    WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "normalPassenger_0"))
    )

    # 选择乘客
    passenger = driver.find_element(By.ID, "normalPassenger_0")
    passenger.click()

    # 提交订单
    submit_button = driver.find_element(By.ID, "submitOrder_id")
    submit_button.click()

    # 等待确认页面
    WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "qr_submit_id"))
    )

    # 确认支付
    confirm_button = driver.find_element(By.ID, "qr_submit_id")
    confirm_button.click()

except Exception as e:
    print(f"发生错误: {e}")

finally:
    # 关闭浏览器
    time.sleep(10)  # 等待10秒后关闭浏览器
    driver.quit()